import {
  Form, Input, Radio, Tree,
} from 'antd'
import React, {
  useCallback, useEffect, useImperativeHandle, useState,
} from 'react'
import { postAdminAddApi, postAdminUpdateApi } from '@/api/auth'
import menu from '@/router/menu'

const SetRootIdAddForm = React.forwardRef((props, ref) => {
  const { detail } = props
  const [role, setRole] = useState(detail?.role || 1)
  const [form] = Form.useForm()
  const handleSubmit = useCallback(async () => {
    const values = await form.validateFields()
    console.log(values)
    if (detail) await postAdminUpdateApi(values)
    else await postAdminAddApi(values)
    return true
  })
  const handleValuesChange = useCallback((val) => {
    if (val.role) setRole(val.role)
  })
  useImperativeHandle(
    ref,
    () => ({
      submit: handleSubmit,
    }),
    [detail],
  )
  useEffect(() => {
    if (!detail) form.setFieldsValue({ role, checkedKeys: ['/general', '/wares', '/wares/store', '/wares/price', '/advertising', '/advertising/fodder', '/advertising/tactics', '/data', '/data/cabinet', '/data/ware', '/set/root', '/set/root/id', '/set/root/role', '/set/root/log'] })
    else {
      setRole(detail[0].role)
      console.log(detail[0].role)
      form.setFieldsValue({ role, ...detail[0] })
    }
  }, [detail])
  return (
    <Form form={form} labelCol={{ span: 4 }} onValuesChange={handleValuesChange}>
      <Form.Item name="adminname" label="用户名" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      {
        !detail && (
          <>
            <Form.Item name="password" label="密码" rules={[{ required: true }]} hasFeedback>
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="confirm"
              label="确认密码"
              rules={[
                {
                  required: true,
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }

                    return Promise.reject(new Error('两次密码不一致'));
                  },
                }),
              ]}
              hasFeedback
            >
              <Input.Password />
            </Form.Item>
          </>
        )
      }
      <Form.Item label="角色" name="role" rules={[{ required: true }]}>
        <Radio.Group>
          <Radio value={1}>管理员</Radio>
          <Radio value={2}>超级管理员</Radio>
        </Radio.Group>
      </Form.Item>
      {
        role === 1 && (
          <Form.Item valuePropName="checkedKeys" trigger="onCheck" label="权限" name="checkedKeys">
            <Tree
              checkable
              defaultExpandAll
              treeData={menu}
            />
          </Form.Item>
        )
      }
    </Form>
  )
})

export default SetRootIdAddForm
